/**
 * 拖拽组件
 * 所有弹窗组件实现拖拽的公用组件
 */

// 将下述模板插入到对话框组件中, 替换title即可
{/* 
  <template #title>
    <div ref="modalTitleRef" style="width: 100%">{{ title }}</div>
  </template>
  <template #modalRender="{ originVNode }">
    <div :style="transformStyle">
      <component :is="originVNode" />
    </div>
  </template>
 */}

export const Draggable = {
  data() {
    return {
      startX: 0,
      startY: 0,
      isDragging: false,
      transformX: 0,
      transformY: 0
    }
  },
  methods: {
    handleMouseMove(event) {
      if (this.isDragging) {
        const offsetX = event.clientX - this.startX;
        const offsetY = event.clientY - this.startY;
        this.transformX += offsetX;
        this.transformY += offsetY;
        this.startX = event.clientX;
        this.startY = event.clientY;
      }
    },
    handleMouseDown(event) {
      this.startX = event.clientX;
      this.startY = event.clientY;
      this.isDragging = true;
    },
    handleMouseUp() {
      this.isDragging = false;
    },
    // 销毁挂载的事件
    removeEventListeners() {
      const modalTitleRef = this.$refs.modalTitleRef;
      // const modalTitleRef = document.querySelector('.ant-modal-header');
      if (modalTitleRef) {
        modalTitleRef.removeEventListener('mousedown', this.handleMouseDown);
      }
      window.removeEventListener('mousemove', this.handleMouseMove);
      window.removeEventListener('mouseup', this.handleMouseUp);
    },
  },
  computed: {
    transformStyle() {
      return {
        transform: `translate(${this.transformX}px, ${this.transformY}px)`,
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      const modalTitleRef = this.$refs.modalTitleRef;
      // const modalTitleRef = document.querySelector('.ant-modal-header');
      if (modalTitleRef) {
        modalTitleRef.style = 'cursor: move'
        modalTitleRef.addEventListener('mousedown', this.handleMouseDown);
      }
      window.addEventListener('mousemove', this.handleMouseMove);
      window.addEventListener('mouseup', this.handleMouseUp);
    });
  },
  beforeUnmount() {
    this.removeEventListeners()
  }
}
